package com.example.demo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Set;


public class BeanUtilsEx extends BeanUtils {
    private static final Logger LOG = LoggerFactory.getLogger(BeanUtilsEx.class);

    static {
        //注册java.sql.Timestamp,java.lang.long,java.lang.Integer,java.math.BigDecimal的转换器
        ConvertUtils.register(new CommonConvert(), java.sql.Date.class);
        ConvertUtils.register(new CommonConvert(), java.sql.Timestamp.class);
        ConvertUtils.register(new CommonConvert(), String.class);
        ConvertUtils.register(new CommonConvert(), Long.class);
        ConvertUtils.register(new CommonConvert(), BigDecimal.class);
        ConvertUtils.register(new CommonConvert(), Boolean.class);
        ConvertUtils.register(new CommonConvert(), Float.class);
        ConvertUtils.register(new CommonConvert(), List.class);
        ConvertUtils.register(new CommonConvert(), Set.class);
    }


    public static void copyProperties(Object source, Object target) {
        try {
            //支持对日期copy
            org.apache.commons.beanutils.BeanUtils.copyProperties(target, source);
        } catch (IllegalAccessException e) {
            LOG.error("BeanUtilsEx IllegalAccessException:" + e.getStackTrace());
           // throw new Exception("BeanUtilsEx IllegalAccessException:");
        } catch (InvocationTargetException ex) {
            LOG.error("BeanUtilsEx InvocationTargetException:" + ex.getStackTrace());
            //throw new Exception("BeanUtilsEx IllegalAccessException:" + ex.getStackTrace());
        }
    }

    public static <T1, T2> void copyList(List<T1> sources, List<T2> targets, Class<T2> targetClass) throws Exception {
        try {
            if (sources != null && sources.size() > 0) {
                for (Object tObj : sources) {
                    T2 sObj = targetClass.newInstance();
                    copyProperties(tObj, sObj);
                    targets.add(sObj);
                }
            }
        } catch (Exception e) {
            throw new Exception("BeanUtilEx error");
        }
    }

}
